<template>
  <div class="container">
    <div class="inputRegion">
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
        "
      >
        <div>
          <span>用户账号：</span>
          <el-input
            v-model="dynamicSelectUserInfo.account"
            placeholder="查找账号"
            style="width: 15%"
            clearable
            @input="inputAccount($event)"
          ></el-input>

          <el-button type="primary" style="margin: 0 20px" @click="queryBtn"
            >查询</el-button
          >

          <span>角色分类：</span>
          <el-select
            v-model="dynamicSelectUserInfo.roleId"
            placeholder="请选择"
            clearable
            style="width: 10%"
            @change="roleChange"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            ></el-option>
          </el-select>

          <span>用户状态：</span>
          <el-select
            v-model="dynamicSelectUserInfo.status"
            placeholder="请选择"
            clearable
            style="width: 10%"
            @change="userStatusChange"
          >
            <el-option
              v-for="item in userStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <el-button type="primary" icon="el-icon-plus" @click="openAddDialog"
          >添加用户</el-button
        >
        <el-button type="danger" icon="el-icon-delete" @click="batchDelUser"
          >批量删除用户</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          @click="triggerFileUpload"
          >批量导入学生</el-button
        >
        <!-- 隐藏的文件选择 input -->
        <input
          ref="excelInput"
          type="file"
          accept=".xls,.xlsx"
          style="display: none"
          @change="handleExcelUpload"
        />
      </div>
    </div>

    <div class="table">
      <el-table
        :data="userData"
        style="width: 100%"
        :border="true"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column type="selection" width="80"></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="account" label="账号" align="center">
        </el-table-column>
        <el-table-column prop="phone" label="电话" align="center">
        </el-table-column>
        <el-table-column label="头像" width="180" align="center">
          <template slot-scope="{ row }">
            <img
              v-if="row.avatar"
              :src="row.avatar"
              style="width: 80px; height: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="100" align="center">
        </el-table-column>

        <el-table-column
          prop="status"
          label="用户状态"
          width="100"
          align="center"
        >
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserStatus(row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column
          prop="updateTime"
          label="更新日期"
          width="200"
          align="center"
        >
        </el-table-column>

        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updateBtn(row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-key"
              size="mini"
              @click="resetPassword(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="dynamicSelectUserInfo.pageNo"
          :page-sizes="[2, 5, 8, 10]"
          :page-size="5"
          layout="total,sizes, prev, pager, next,jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!--添加表单-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      style="margin-top: -120px"
    >
      <el-form :model="form" :rules="rules" ref="addForm">
        <el-form-item
          label="账号:"
          prop="account"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.account"
            autocomplete="off"
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="用户名:"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.username"
            autocomplete="off"
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机号:"
          :label-width="formLabelWidth"
          prop="phone"
        >
          <el-input
            v-model="form.phone"
            autocomplete="off"
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" :label-width="formLabelWidth" prop="email">
          <el-input
            v-model="form.email"
            autocomplete="off"
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="用户角色:"
          prop="roleList"
          :label-width="formLabelWidth"
        >
          <el-checkbox-group v-model="form.roleList" @change="checkBoxChange">
            <el-checkbox
              v-for="role in roleList"
              :key="role.id"
              :label="role.id"
              :disabled="isDisabled(role.id)"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item
          label="所属系:"
          prop="departmentId"
          :label-width="formLabelWidth"
        >
          <el-select
            :popper-append-to-body="false"
            v-model="form.departmentId"
            placeholder="请选择系"
            @change="onDepartmentChange"
            :disabled="isOnlyAdminRole"
            style="width: 40%"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="所属专业:"
          prop="majorId"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.majorId"
            placeholder="请选择专业"
            @change="onMajorChange"
            :disabled="!majors.length || isOnlyAdminRole"
            style="width: 40%"
          >
            <el-option
              v-for="major in majors"
              :key="major.id"
              :label="major.majorName"
              :value="major.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="所属年级:"
          prop="gradeId"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.gradeId"
            placeholder="请选择年级"
            @change="onGradeChange"
            :disabled="!grades.length || isOnlyAdminRole"
            style="width: 40%"
          >
            <el-option
              v-for="grade in grades"
              :key="grade.id"
              :label="grade.gradeName"
              :value="grade.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="所属班级:"
          prop="classId"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.classId"
            placeholder="请选择班级"
            :disabled="!classes.length || isOnlyAdminRole"
            style="width: 40%"
          >
            <el-option
              v-for="cls in classes"
              :key="cls.id"
              :label="cls.className"
              :value="cls.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改表单部分 -->
    <el-dialog title="修改用户信息" :visible.sync="updateDialogFormVisible">
      <el-form :model="updateForm" ref="updateForm" :rules="updateRules">
        <!-- 基础信息字段 -->
        <el-form-item label="账号" :label-width="formLabelWidth">
          <el-input v-model="updateForm.account" disabled></el-input>
        </el-form-item>

        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="updateForm.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="updateForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>
        <!-- 动态教育信息 -->
        <!-- 教师显示系 -->
        <el-form-item
          v-if="hasTeacherRole"
          label="所属系"
          :label-width="formLabelWidth"
          prop="departmentId"
        >
          <el-select
            v-model="updateForm.departmentId"
            @change="handleDepartmentChange"
            disabled
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <!-- 学生显示完整路径 -->
        <template v-if="hasStudentRole">
          <!-- 系选择 -->
          <el-form-item
            label="所属系"
            :label-width="formLabelWidth"
            prop="departmentId"
          >
            <el-select
              :popper-append-to-body="false"
              v-model="updateForm.departmentId"
              @change="handleDepartmentChange"
              disabled
            >
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.deptName"
                :value="dept.id"
              />
            </el-select>
          </el-form-item>

          <!-- 专业选择 -->
          <el-form-item
            label="所属专业"
            :label-width="formLabelWidth"
            prop="majorId"
          >
            <el-select
              v-model="updateForm.majorId"
              placeholder="请选择专业"
              @change="handleUpdateMajorChange"
              disabled
            >
              <el-option
                v-for="major in updateMajors"
                :key="major.id"
                :label="major.majorName"
                :value="major.id"
              />
            </el-select>
          </el-form-item>

          <!-- 年级选择 -->
          <el-form-item
            label="所属年级"
            :label-width="formLabelWidth"
            prop="gradeId"
          >
            <el-select
              v-model="updateForm.gradeId"
              placeholder="请选择年级"
              @change="handleUpdateGradeChange"
              disabled
            >
              <el-option
                v-for="grade in updateGrades"
                :key="grade.id"
                :label="grade.gradeName"
                :value="grade.id"
              />
            </el-select>
          </el-form-item>

          <!-- 班级选择 -->
          <el-form-item
            label="所属班级"
            :label-width="formLabelWidth"
            prop="classId"
          >
            <el-select v-model="updateForm.classId" disabled>
              <el-option
                v-for="cls in updateClasses"
                :key="cls.id"
                :label="cls.className"
                :value="cls.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer">
        <el-button @click="updateDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllUserByPage,
  updateUserStatusById,
  deleteUserByIds,
  deleteUserById,
} from "@/api/user";
import {
  addUser,
  updataUser,
  batchInsertUser,
  resetUserPassword,
} from "@/api/user";
import { getAllRoleInfo } from "@/api/role";
import { getMajorByDeptId } from "@/api/major";
import { getAllGrade } from "@/api/grade";
import { getClassByMajorIdAndGradeId, getClassById } from "@/api/class";
import { mapState } from "vuex";
export default {
  name: "UserManage",
  data() {
    const validatorRole = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error("请选择至少一个角色"));
      } else {
        // 逻辑冲突校验
        const conflictMap = {
          1: [3], // 管理员不能和学生
          2: [3], // 老师不能和学生
          3: [1, 2], // 学生不能和管理员或老师
        };

        for (let i = 0; i < value.length; i++) {
          const current = value[i];
          const conflictRoles = conflictMap[current] || [];
          for (let j = 0; j < value.length; j++) {
            if (i !== j && conflictRoles.includes(value[j])) {
              callback(new Error("所选角色之间存在冲突，请重新选择"));
              return;
            }
          }
        }

        callback(); // 无错误
      }
    };

    const validateDepartmentForRole = (rule, value, callback) => {
      const selectedRoles = this.form.roleList; // 当前选中的角色 ID 数组
      const roleMap = this.roleList.reduce((map, role) => {
        map[role.id] = role.name;
        return map;
      }, {});

      const departmentId = value;

      let hasAdmin = selectedRoles.some(
        (roleId) => roleMap[roleId] === "管理员"
      );
      let hasOther = selectedRoles.some(
        (roleId) => roleMap[roleId] !== "管理员"
      );

      if (hasAdmin && departmentId) {
        return callback(new Error("管理员不能选择所属系"));
      }

      if (hasOther && !departmentId) {
        return callback(new Error("请选择所属系"));
      }

      callback(); // 校验通过
    };

    return {
      loading: true,
      fileLoading: false, // 文件上传全屏加载
      userData: [],
      multipleSelection: [],
      total: 1,
      // 用户状态选择
      userStatus: [
        {
          value: 0,
          label: "禁用",
        },
        {
          value: 1,
          label: "启用",
        },
      ],
      // 展示角色信息
      roleList: [],

      // 收集信息发送请求，动态查询
      dynamicSelectUserInfo: {
        pageNo: 1, // 页数
        pageSize: 5, // 每页展示数量
        account: "",
        roleId: "",
        status: "",
      },

      userIds: [], // 选择的用户id

      dialogFormVisible: false,
      updateDialogFormVisible: false, // 修改的表单
      form: {
        account: "",
        username: "",
        phone: null,
        email: null,
        roleList: [],
        departmentId: "",
        majorId: "",
        gradeId: "",
        classId: "",
      },

      // 修改用户信息表单
      updateForm: {
        // 原有字段
        id: null,
        account: "",
        username: "",
        phone: null,
        email: null,
        roleList: [],
        departmentId: null,
        majorId: null,
        gradeId: null,
        classId: null,
      },
      updateMajors: [],
      updateClasses: [],
      updateGrades: [],

      updateRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        phone: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: ["blur", "change"],
          },
        ],
        email: [{ type: "email", message: "邮箱格式不正确", trigger: "blur" }],
      },

      formLabelWidth: "120px",
      rules: {
        account: [
          { required: true, message: "请输入用户账号", trigger: "change" },
          {
            min: 6,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
        ],
        roleList: [
          {
            type: "array",
            validator: validatorRole,
            required: true,
            trigger: "change",
          },
        ],

        departmentId: [
          {
            required: true,
            validator: validateDepartmentForRole,
            trigger: "change",
          },
        ],

        phone: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: ["blur", "change"],
          },
        ],
        email: [{ type: "email", message: "邮箱格式不正确", trigger: "blur" }],
      },
      grades: [],
      majors: [],
      classes: [],

      conflictMap: {
        1: [3], // 管理员不能和学生
        2: [3], // 老师不能和学生
        3: [1, 2], // 学生互相排斥
      },
    };
  },

  computed: {
    isOnlyAdminRole() {
      // 判断是否仅选择了管理员（1）
      if (this.form.roleList.length == 0) {
        return true;
      }
      return this.form.roleList.length === 1 && this.form.roleList[0] === 1;
    },
    ...mapState("dept", ["departments"]),

    showDept() {
      return this.form.roleId === 3 || this.form.roleId === 2;
    },
    showMajor() {
      return this.form.roleId === 3;
    },
    showGrade() {
      return this.form.roleId === 3;
    },
    showClass() {
      return this.form.roleId === 3;
    },

    hasTeacherRole() {
      return this.updateForm.roleIds?.includes(2);
    },

    hasStudentRole() {
      return this.updateForm.roleIds?.includes(3);
    },
  },
  mounted() {
    // 获取分页信息
    this.getAllUserData(this.dynamicSelectUserInfo);
    // 获取角色信息
    this.getAllRoleData();
    this.getAllDeptInfo();
    if (this.departments.length === 0) {
      this.getAllDeptInfo();
    }
  },

  methods: {
    // 获取所有系的id和name
    getAllDeptInfo() {
      this.$store.dispatch("dept/getAllDept");
    },
    openAddDialog() {
      this.dialogFormVisible = true;
      // 如果部门数据为空，则重新获取
      this.$nextTick(() => {
        this.$refs.addForm.resetFields();
        this.form = {
          account: "",
          username: "",
          phone: null,
          email: null,
          roleList: [],
          departmentId: "",
          majorId: "",
          gradeId: "",
          classId: "",
        }; // 重置表单
      });
    },

    // 获取所有系的id和name
    getAllDeptInfo() {
      this.$store.dispatch("dept/getAllDept");
    },
    // 冲突映射表
    isDisabled(roleId) {
      if (this.form.roleList.includes(roleId)) return false;
      return this.form.roleList.some((selectedRole) => {
        return (
          this.conflictMap[selectedRole] &&
          this.conflictMap[selectedRole].includes(roleId)
        );
      });
    },
    // 部门
    async onDepartmentChange(deptId) {
      this.form.majorId = "";
      this.form.gradeId = "";
      this.form.classId = "";

      // 如果角色中没有学生就不展示专业等其他信息
      if (!this.form.roleList.includes(3)) {
        return;
      }
      // 根据系id信息查找对应的 major
      try {
        let res = await getMajorByDeptId(deptId);
        this.majors = res.data;
      } catch (e) {}
      this.grades = [];
      this.classes = [];
    },

    //专业
    async onMajorChange() {
      this.form.gradeId = "";
      this.form.classId = "";
      try {
        //查询所有年级
        let res = await getAllGrade();
        this.grades = res.data;
      } catch (e) {}
      this.classes = [];
    },

    async onGradeChange() {
      this.form.classId = "";
      const { majorId, gradeId } = this.form;
      try {
        let res = await getClassByMajorIdAndGradeId(gradeId, majorId);
        this.classes = res.data || [];
      } catch (e) {}
    },

    checkBoxChange(newVal) {
      const hasStudent = newVal.includes(3);
      const hasAdminOrTeacher = newVal.includes(1) || newVal.includes(2);
      if (!hasStudent || hasAdminOrTeacher) {
        // 清空详细信息
        this.form.departmentId = "";
        this.form.majorId = "";
        this.form.gradeId = "";
        this.form.classId = "";
        // 清空下拉框可选项
        this.majors = [];
        this.grades = [];
        this.classes = [];
      }

      // 基础规则
      const rules = {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        account: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: ["blur", "change"],
          },
        ],
        email: [
          {
            type: "email",
            message: "邮箱格式不正确",
            trigger: ["blur", "change"],
          },
        ],
      };
      // 根据角色 id 设置额外校验
      if (this.form.roleList.includes(3)) {
        // 学生：需要院系、专业、年级、班级
        rules.departmentId = [
          { required: true, message: "请选择院系", trigger: "change" },
        ];
        rules.majorId = [
          { required: true, message: "请选择专业", trigger: "change" },
        ];
        rules.gradeId = [
          { required: true, message: "请选择年级", trigger: "change" },
        ];
        rules.classId = [
          { required: true, message: "请选择班级", trigger: "change" },
        ];
      } else if (this.form.roleList.includes(2)) {
        // 老师：只需要院系
        rules.departmentId = [
          { required: true, message: "请选择院系", trigger: "change" },
        ];
      }
      // 应用新的规则
      this.rules = rules;
    },

    //添加用户表单
    addUser() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.form.phone == "") {
              this.form.phone = null;
            }
            if (this.form.email == "") {
              this.form.email = null;
            }
            let res = await addUser(this.form);
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.data,
              });
              this.dialogFormVisible = false;
              this.getAllUserData(this.dynamicSelectUserInfo);
            } else {
              this.$message({
                type: "error",
                message: res.msg || "添加失败",
              });
            }
          } catch (error) {
            this.$message.error("添加用户失败");
          }
        } else {
          this.$message.error("请检查表单信息是否正确");
          return false;
        }
      });
    },
    // 分页查询用户信息
    async getAllUserData(dynamicSelectUserInfo) {
      this.loading = true;
      try {
        let res = await getAllUserByPage(dynamicSelectUserInfo);
        // 将所需要使用的数据解构出来
        let { total, records } = res.data;
        this.userData = records;
        this.total = total;
      } catch (e) {
      } finally {
        this.loading = false;
      }
    },

    // 获取所有角色信息
    async getAllRoleData() {
      this.roleList = [];
      try {
        let res = await getAllRoleInfo();
        this.roleList = res.data || [];
      } catch (e) {}
    },

    handleSelectionChange(userInfo) {
      this.userIds = [];
      //构建出删除的用户id
      userInfo.forEach((user) => {
        this.userIds.push(user.id);
      });
    },

    // 分页size改变
    handleSizeChange(pageSize) {
      this.dynamicSelectUserInfo.pageSize = pageSize;
      this.getAllUserData(this.dynamicSelectUserInfo);
    },

    // 页码发生改变
    handleCurrentChange(pageNo) {
      this.dynamicSelectUserInfo.pageNo = pageNo;
      this.getAllUserData(this.dynamicSelectUserInfo);
    },

    // 用户状态发生改变时的回调
    async changeUserStatus(row) {
      let { id, status } = row;
      try {
        await this.$confirm(
          `确认要${row.status === 1 ? "启用" : "禁用"}该用户吗？`,
          "提示",
          {
            type: "warning",
          }
        );
        let res = await updateUserStatusById(id, status);
        if (res.code == 200) {
          this.$message({
            type: "success",
            duration: 2000,
            message: "修改状态成功",
          });
          this.getAllUserData(this.dynamicSelectUserInfo);
        } else {
          this.$message({
            type: "error",
            duration: 2000,
            message: "修改状态失败",
          });
          row.status = row.status == 1 ? 0 : 1;
        }
      } catch (e) {
        row.status = row.status == 1 ? 0 : 1;
      }
    },

    // 用户状态选择发生改变
    userStatusChange(newVal) {
      this.dynamicSelectUserInfo.status = newVal;
      this.getAllUserData(this.dynamicSelectUserInfo);
    },

    // 选择角色发生改变
    roleChange(newVal) {
      this.dynamicSelectUserInfo.roleId = newVal;
      this.getAllUserData(this.dynamicSelectUserInfo);
    },

    queryBtn() {
      // 如果当前页码数大于1
      this.dynamicSelectUserInfo.pageNo =
        this.dynamicSelectUserInfo.pageNo > 1 ? 1 : 1;
      //点击按钮发送请求获取数据
      this.getAllUserData(this.dynamicSelectUserInfo);
    },

    inputAccount(e) {
      let { account } = this.dynamicSelectUserInfo;
      // 如果输入为空发送请求
      if (account == "") {
        this.getAllUserData(this.dynamicSelectUserInfo);
      }
    },

    async batchDelUser() {
      if (!this.userIds.length) {
        this.$message("尚未选择用户");
        return;
      }

      // 删除用户
      try {
        let result = await this.$confirm(
          "此操作将会删除该用户, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
        let res = await deleteUserByIds(this.userIds);
        console.log("删除用户", res);

        if (res.code == 200) {
          this.$message({
            type: "success",
            message: res.data,
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg || "删除失败",
          });
        }
      } catch (e) {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      }
    },

    async deleteUser({ id }) {
      try {
        let result = await this.$confirm(
          "此操作将会删除该用户, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 删除前记录当前数据总量
        const originalTotal = this.total;

        // 执行删除操作
        let res = await deleteUserById(id);
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: res.data,
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg || "删除失败",
          });
        }

        // 计算新的页码逻辑
        const newTotal = originalTotal - 1; // 总数据量减1
        const pageSize = this.dynamicSelectUserInfo.pageSize;
        const newTotalPages = Math.ceil(newTotal / pageSize);

        // 如果当前页码超出最大页数，自动跳转前一页
        if (this.dynamicSelectUserInfo.pageNo > newTotalPages) {
          this.dynamicSelectUserInfo.pageNo = Math.max(1, newTotalPages);
        }
        // 重新获取数据
        await this.getAllUserData(this.dynamicSelectUserInfo);
      } catch (e) {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      }
    },

    // 点击修改操作，初始化回显
    async updateBtn(row) {
      // 重置表单
      this.updateForm = {
        id: null,
        account: "",
        username: "",
        phone: "",
        email: "",
        roleList: [],
        departmentId: null,
        majorId: null,
        gradeId: null,
        classId: null,
      };
      this.updateDialogFormVisible = true;

      if (row.classId) {
        let res = await getClassById(row.classId);
        this.updateClasses = [res.data];
        this.updateForm = {
          ...row,
          departmentId: row.deptId,
          majorId: res.data.majorId,
          gradeId: res.data.gradeId,
          classId: row.classId,
          roleList: row.roleIds,
        };
      } else {
        this.updateClasses = [];
        this.updateForm = { ...row, departmentId: row.deptId };
      }

      // 加载年级
      if (row.classId) {
        let res = await getAllGrade();
        this.updateGrades = res.data || [];

        //加载班级
        let resCls = await getClassByMajorIdAndGradeId(
          this.updateForm.gradeId,
          this.updateForm.majorId
        );

        this.updateClasses = resCls.data || [];
      }

      // 初始化调用部门变更，传 true 表示初始化调用，不清空下级选项
      if (this.updateForm.departmentId) {
        await this.handleDepartmentChange(this.updateForm.departmentId, true);
      }
    },

    // 处理系部变更
    async handleDepartmentChange(deptId, isInit = false) {
      if (!isInit) {
        // 用户主动切换系部时，清空下级选择和选项列表
        this.updateForm.majorId = null;
        this.updateForm.gradeId = null;
        this.updateForm.classId = null;
        this.updateMajors = [];
        this.updateClasses = [];
      }

      if (deptId) {
        try {
          const res = await getMajorByDeptId(deptId);
          this.updateMajors = res.data || [];
        } catch (error) {
          this.$message.error("专业加载失败");
        }
      }
    },

    // 选择专业时清空年级和班级
    async handleUpdateMajorChange(majorId) {
      this.updateForm.classId = null;
      this.updateClasses = [];
    },

    // 选择年级时加载班级
    async handleUpdateGradeChange(gradeId) {
      this.updateForm.classId = null;
      if (this.updateForm.majorId && gradeId) {
        await this.loadUpdateClasses(this.updateForm.majorId, gradeId);
      } else {
        this.updateClasses = [];
      }
    },

    // 加载班级
    async loadUpdateClasses(majorId, gradeId) {
      try {
        const res = await getClassByMajorIdAndGradeId(gradeId, majorId);
        this.updateClasses = res.data || [];
      } catch (error) {
        this.$message.error("班级加载失败");
      }
    },

    // 完善提交方法
    submitUpdate() {
      this.$refs.updateForm.validate(async (valid) => {
        if (valid) {
          try {
            // 构造提交数据
            const payload = {
              id: this.updateForm.id,
              username: this.updateForm.username,
              phone: this.updateForm.phone,
              email: this.updateForm.email,
              roleList: this.updateForm.roleIds,
            };

            // 调用更新接口
            let res = await updataUser(payload);
            this.$message.success("修改成功");
            this.updateDialogFormVisible = false;

            this.getAllUserData(this.dynamicSelectUserInfo);
          } catch (error) {
            this.$message.error("修改失败");
          }
        } else {
          return false;
        }
      });
    },

    // 点击按钮时触发隐藏的文件选择框
    triggerFileUpload() {
      this.$refs.excelInput.click();
    },

    // 文件选择完成后处理 Excel 文件
    async handleExcelUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 可选：判断文件类型
      const isExcel = /\.(xls|xlsx)$/.test(file.name);
      if (!isExcel) {
        this.$message.error("请上传 Excel 文件（.xls 或 .xlsx）");
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      const loading = this.$loading({
        lock: true,
        text: "文件上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      try {
        let res = await batchInsertUser(formData);
        if (res.code == 200) {
          this.$message.success(res.data || "导入成功");
          // 可选：刷新数据
          this.getAllUserData(this.dynamicSelectUserInfo);
        } else {
          this.$message.error(res.msg || "导入失败");
        }
      } catch (error) {
        this.$message.error(
          "导入失败：" + (error.response?.data?.message || error.msg)
        );
      } finally {
        loading.close();
      }
      // 清空 input 的值，避免选同一个文件无法再次触发 change
      event.target.value = "";
    },

    // 重置用户密码
    async resetPassword(row) {
      try {
        await this.$confirm("确认要重置该用户密码吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const res = await resetUserPassword(row.id);
        if (res.code === 200) {
          this.$message.success("密码重置成功");
        } else {
          this.$message.error(res.msg || "密码重置失败");
        }
      } catch (error) {
        this.$message.info("已取消重置密码操作");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-message {
  z-index: 9999 !important;
}
.container {
  margin: 20px;
  span {
    font-weight: 800;
    color: #333;
    margin: 0 10px;
  }
  .inputRegion {
    margin: 30px 0;
  }
  .table {
    margin-top: 20px;
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
      margin-top: 50px;
    }
  }
}
</style>